import appConfig from '@/utils/appConfig'
import request from '@/utils/request'
import { useRequest } from 'ahooks'
import { createGlobalStore } from 'hox'
import useAwaitAsync from '../hook/useAwaitAsync'
import { useNetworkStore } from './networkStore'

const generateToken = (params: { appConfigId: string }): Promise<{ token: string }> => request.post('/api/ThirdParty/GenerateToken', params)

type AwaitBeforeInitReturnType = Exclude<PromiseReturnType<ReturnType<BeforeInitUsedType>>, undefined>
type BeforeInitUsedType = Exclude<typeof appConfig.beforeInit, undefined>

export const [useInitStore, getInitStore] = createGlobalStore(() => {
    useNetworkStore()
    const { beforeInit } = appConfig
    // 初始化前执行异步方法
    const beforeInitApi = useRequest<PromiseReturnType<ReturnType<BeforeInitUsedType>>, []>(beforeInit as any, {
        ready: Boolean(beforeInit),
    })
    const { awaitAsync: awaitBeforeInit } = useAwaitAsync<AwaitBeforeInitReturnType>(!beforeInit ? true : beforeInitApi.data, res => !!res)

    return {
        initReady: true,
        awaitBeforeInit,
        beforeInitRes: beforeInitApi.data,
    }
})